//
//  AddToPlotViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 06/04/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "AddToPlotViewController.h"
#import "Plot.h"
#import "Bed.h"
#import "Plot+CRUD.h"
#import "AppDelegate.h"
#import "Plant.h"
#import "PlotIncompatibilty+CRUD.h"
#import "UILabel+TextFont.h"

@interface AddToPlotViewController()
@property (nonatomic, strong) Plot *plot;
@property (nonatomic, strong) NSArray *plotsArray;
@property (nonatomic, strong) NSArray *beds;
@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic, strong) NSArray *selectedBeds;
@end

@implementation AddToPlotViewController

@synthesize plotLabel = _plotLabel;
@synthesize plotPicker = _plotPicker;
@synthesize tableView = _tableView;
@synthesize plantsToAdd = _plantsToAdd;
@synthesize plot = _plot;
@synthesize plotsArray = _plotsArray;
@synthesize beds = _beds;
@synthesize context = _context;
@synthesize selectedBeds = _selectedBeds; 
#pragma mark - View lifecycle


- (void)viewDidLoad
{
    [super viewDidLoad];
    //Get the managedObjectContext from the AppDelegate
    self.context = [(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext];
    //Load a list of all plots
    self.plotsArray = [Plot loadAllPlotsInContext:self.context];
    
    //Set a clear background color on the table
    self.tableView.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.backgroundColor = [UIColor clearColor];
    
    
    self.plotPicker.frame = CGRectMake(0, 40, 300, 200);
    [self.plotLabel setMVBoliFont];
    //Set the delegate of the picker
    self.plotPicker.delegate = self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //Get the currently selected row in the picker
    int row = [self.plotPicker selectedRowInComponent:0];
    self.plot = [self.plotsArray objectAtIndex:row];
    
    //Get a list of all the beds in the plot
    self.beds = [NSArray arrayWithArray:[self.plot.beds allObjects]];
    
    //Set up the bed table to allow multi selection
    self.tableView.editing = YES;
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [self setPlotPicker:nil];
    [self setPlotLabel:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Picker View Delegate

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.plot = [self.plotsArray objectAtIndex:row];
    //Reload the list of beds when a new plot is selected
    self.beds = [NSArray arrayWithArray:[self.plot.beds allObjects]];
    [self.tableView reloadData];
}

#pragma mark - Picker View Datasource

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.plotsArray count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    Plot *plot = [self.plotsArray objectAtIndex:row];
    return plot.name;
}

#pragma mark - TableView Delegate

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"bedCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    Bed *bed = [self.beds objectAtIndex:indexPath.row];
    cell.textLabel.text = bed.name;
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    
    //Make the cell transparent with no border
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    UIView *bgView = [[UIView alloc] init];
    bgView.frame = cell.frame;
    [bgView setBackgroundColor:[UIColor clearColor]];
    [cell setSelectedBackgroundView:bgView];
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"Select Bed(s)";
}

/*Create custom label view for the secions header*/
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:self.tableView titleForHeaderInSection:section]; 
    UILabel *header = [[UILabel alloc] init];
    header.frame = CGRectMake(125, 10, 284, 23);
    header.text = sectionTitle;
    [header setMVBoliFont];
    header.backgroundColor = [UIColor clearColor];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(250, 0, 320, 10)];
    [view addSubview:header];
    return view;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.beds count];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedBeds = [tableView indexPathsForSelectedRows];
}

#pragma mark - Button Actions

- (IBAction)cancelPressed:(UIBarButtonItem *)sender 
{
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

/*Create incompatibilites for the plants in the bed*/
-(void)saveAnyIncompatibilities:(Bed *)bed
{
    //Iterate over the list of plants in the bed
    for (Plant *plant in bed.plants) {
        //check every plant in the bed against every other plant. See if there are any incompatibilies. If there are create a record
        for (Plant *plantToCheck in bed.plants) {
            
            if([plant.incompatibles containsObject:plantToCheck]){
               
                [PlotIncompatibilty createPlotIncompatibiltyForPlant:plant andPlant:plantToCheck inBed:bed withContext:self.context];
            }
        }
    }
}



- (IBAction)savePressed:(UIBarButtonItem *)sender 
{
    for (NSIndexPath *indexPath in self.selectedBeds) {
        Bed *bed = [self.beds objectAtIndex:indexPath.row];
        for (Plant *plant in self.plantsToAdd) {
            [bed addPlantsObject:plant];
        }
        //Create an incompatibility object for any plants that are incompatible in the bed.
        [self saveAnyIncompatibilities:bed];
    }       
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}
@end
